package com.itany.corejava.day18;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

public class ChatServer {
	// 保留每一个聊天客户对应的Socket对象
	private Set<Socket> clients;
	private List<String> list;
	public void init() {
		list=new ArrayList<String>();
		clients = new HashSet();
		try {
			ServerSocket ss = new ServerSocket(9999);
			System.out.println("Chat Server started.");
			while (true) {
				Socket socket = ss.accept();
				clients.add(socket);
				BufferedReader br=new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
				String username=br.readLine();
				System.out.println(username);
				list.add(username);
				String str="";
				for (int i = 0; i < list.size(); i++) {
					str+=list.get(i)+",";
				}
				str=str.substring(0, str.length()-1);
				for (Socket s : clients) {
					PrintWriter pw=new PrintWriter(s.getOutputStream());
					pw.println("login#"+str);
					pw.flush();
				}
				System.out.println(socket.getInetAddress());
				ChatServerThread cst = new ChatServerThread(socket, clients,list);
				cst.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new ChatServer().init();
	}
}

class ChatServerThread extends Thread {
	private Socket socket;

	private Set<Socket> clients;// 所有聊天用户socket对象的集合

	private List<String> list;
	
	public ChatServerThread(Socket s, Set clients,List<String> list) {
		this.socket = s;
		this.clients = clients;
		this.list=list;
	}

	// 反复接受这个客户发过来的聊天内容
	// 接受到聊天内容后，把这个聊天内容广播给所有的聊天用户
	// 这个用户退出了，不用接受这个用户的输入，这个线程结束
	// 从用户Socket的集合中，移除当前Socket对象
	public void run() {
		try {
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			while (true) {
				String s = br.readLine();
				if (s.indexOf("#exit") != -1) {
					String[] arr = s.split("#");
					clients.remove(socket);
					is.close();
					socket.close();
					String ss=arr[2] + ",exit";
					System.out.println(ss);
//					BASE64Encoder en=new BASE64Encoder();
//					ss=en.encode(ss.getBytes());
					broadcast(ss, clients);
					list.remove(arr[2]);
					String str="";
					for (int i = 0; i < list.size(); i++) {
						str+=list.get(i)+",";
					}
					if(str.length()!=0){
						str=str.substring(0, str.length()-1);
						list.remove(arr[2]);
						for (Socket c : clients) {
							PrintWriter pw=new PrintWriter(c.getOutputStream());
							pw.println("exit#"+str);
							pw.flush();
						}
					}
					break;
				}

				broadcast(s, clients);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 把当前用户输入聊天内容，广播给所有的聊天用户
	private void broadcast(String str, Set clients) {
//		for (Socket s : clients) {
		Iterator it=clients.iterator();
		while(it.hasNext()){
			Socket s=(Socket) it.next();
			try {
				PrintWriter pw = new PrintWriter(s.getOutputStream());
				pw.println(str);
				pw.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

